package dao

import (
	"errors"
	__ "order-srv/basic/proto"
	"order-srv/handler/models"
)

/*
AddressCreate 新增收货地址
	业务说明:
	1. 校验用户是否存在。
	2. 统计该用户现有地址数量，若为 0，则将本次新增地址设为默认地址；否则设为非默认地址。
	3. 组装地址实体并写入数据库。
	4. 基础字段校验：姓名/手机/省/市/区/详细地址不能为空。
*/
// 收货地址添加
func AddressCreate(in *__.AddressCreateReq, address models.Address) error {
	// 1. 基础字段校验：姓名/手机/省/市/区/详细地址不能为空
	if in.RecipientName == "" || in.Mobile == "" || in.Province == "" || in.City == "" || in.District == "" || in.DetailAddress == "" {
		return errors.New("信息不能为空")
	}

	var user models.User
	user.Id = uint(in.UserId)
	if err := user.GetUserExistence(); err != nil {
		return err
	}
	if user.UStatus == 2 {
		return errors.New("该用户被冻结")
	}
	
	// 2. 判断用户是否已有地址
	count, err := address.CountByUser(in.UserId)
	if err != nil {
		return err
	}
	
	// 3. 确定是否设为默认地址
	// 如果用户没有地址，则新地址设为默认
	isDefault := count == 0
	add := models.Address{
		UserId:        uint(in.UserId),
		RecipientName: in.RecipientName,
		Mobile:        in.Mobile,
		Province:      in.Province,
		City:          in.City,
		District:      in.District,
		DetailAddress: in.DetailAddress,
		ReceiverZip:   in.ReceiverZip,
		IsDefault:     isDefault,
	}
	
	if err := add.AddressCreate(); err != nil {
		return errors.New("收货地址添加失败")
	}
	
	return nil
}

// 收货地址列表
func AddressList(in *__.AddressListReq, address models.Address) ([]*__.AddressList, error) {
	address.UserId = uint(in.UserId) // 修复：在查询之前设置UserId
	list, err := address.AddressList()
	if err != nil {
		return nil, errors.New("查询收货地址列表失败")
	}
	var listAddress []*__.AddressList
	for _, v := range list {
		var isDefaultInt int64
		if v.IsDefault {
			isDefaultInt = 1
		} else {
			isDefaultInt = 0
		}
		listAddress = append(listAddress, &__.AddressList{
			Id:            int64(v.Id), // 修复：添加缺失的Id字段
			UserId:        int64(v.UserId),
			RecipientName: v.RecipientName,
			Mobile:        v.Mobile,
			Province:      v.Province,
			City:          v.City,
			District:      v.District,
			DetailAddress: v.DetailAddress,
			ReceiverZip:   v.ReceiverZip,
			IsDefault:     isDefaultInt,
		})
	}
	return listAddress, err
}

// 收货地址删除
func AddressDel(in *__.AddressDelReq) error {
	var address models.Address
	address.Id = uint(in.Id)
	if err := address.AddressDelete(); err != nil {
		return errors.New("收货地址删除失败")
	}
	return nil
}
